//点击登录按钮后获取到的页面
var loginHtml;
//抓多张卡的时候用来表示第几张卡的索引
var indexOfCard = 0;
//账单日
var billDay;
var timeout = null;
//浦发银行客户号
var account;
var showTimes = 0;
//是否正确输入
var isInput = false;
//账单调用出现网络异常时处理变量
var billIndex = 1;
var v4_spd_credit_java_funcs = {
    openHomePage : function(){
        var loginUrl = "https://ebill.spdbccc.com.cn/cloudbank-portal/loginController/toLogin.action";
        var loginText = get(loginUrl);
        // var loginText = "HTTP 400 错误的请求";
        var loginIndex = 1;
        do {
            if(loginText.contains("HTTP 400 错误的请求")){
                logger.info("SPD taskKey：{} 第 {} 次重新发起请求 ",context.get(LUA_TASK_KEY),loginIndex);
                loginText = get(loginUrl);
                // 等待三秒钟;
                luaFuncs.threadSleep();
                loginIndex++;
            }
            storeDataToFile(context, loginText, loginIndex + "_login_html.html");
        }while (loginText.contains("HTTP 400 错误的请求") && loginIndex < 10)
        context.put("loginText", loginText);
    },
    checkProxyAvailable : function() {
        var loginText = context.get("loginText");
        //根据返回页面信息判断是不是代理ip异常
        if (loginText.contains("HTTP 400 错误的请求") ) {
            logger.info("SPD taskKey = " + context.get(LUA_TASK_KEY) + " 代理IP异常");
            return false;
        } else {
            return true;
        }
    },
    checkTargetWebsiteAvailable: function(){
        return true;
    },
    /*检查控件是否可用*/
    checkControlAvailable :function () { return true },
    //只有在图片验证码错误或短信验证码错误　重置环境  BALO_21301_10
    needResetEnvironment :function () {
        return  equals(context.get("currentErrorCode"),BALO_99602_50) || equals(context.get("currentErrorCode"),BALO_99602_40);
    },
    login: function() {
        showTimes = System.nanoTime();   //用来计算窗口show的时间
        var idNoIsExist = is_exist_by_id("idNo");
        if(idNoIsExist){
            logger.info("任务【 {} 】页面加载成功", context.get(LUA_TASK_KEY));
        }else {
            logger.info("任务【 {} 】页面加载失败", context.get(LUA_TASK_KEY));
            throwBankExceptionByErrorCode(BALO_99601_30);
        }
        var idNo = getLoginParams(context)[0];
        //输入图片验证码
        inputIdCard(idNo);
        var imgIndex = 1;
        var isValidImgCode = false;
        do {
            isValidImgCode = false;
            //显示窗口
            luaFuncs.setSizeAndShow();
            // 获取图片验证码
            getImgValidCode();
            //输入图片验证码
            var captcha = inputImgValidCode();
            Thread.sleep(1000);        // 验证图片验证码是否正确
            var imgValidCodeResultUrl = "https://ebill.spdbccc.com.cn/cloudbank-portal/loginController/pictureCode.action";
            var paramsMap = new HashMap();
            paramsMap.put("idNo", idNo);
            paramsMap.put("idType", "01");
            paramsMap.put("code", captcha);
            paramsMap.put("ptcId", "1");
            logger.info("浦发云账单,任务{} 第{}次发送验证图片验证码是否正确",context.get(LUA_TASK_KEY),imgIndex);
            var  imgCodeHtml = ajax_post(imgValidCodeResultUrl, paramsMap);
            // var  imgCodeHtml = "return is null"; 503 Service Unavailable
            logger.info("浦发云账单,任务{} 第{}次发送验证图片验证码是否正确,请求结果为：{}",context.get(LUA_TASK_KEY),imgIndex,imgCodeHtml);
            if(imgCodeHtml.contains("return is null") || imgCodeHtml.contains("9DhefwqGPrzGxEp9hPaoag") || imgCodeHtml.contains("503 Service Unavailable")){
                logger.info("浦发云账单,任务{} 第{}次发送验证图片验证码错误",context.get(LUA_TASK_KEY),imgIndex);
                break;
            }else{
                if(StringUtils.isNotBlank(imgCodeHtml)){
                    var imgCodeJSON = JSON.parse(imgCodeHtml);
                    if(imgCodeJSON != undefined){
                        var imgValidResult = imgCodeJSON.get("result");
                        if (StringUtils.isNotBlank(imgValidResult)){
                            if(imgValidResult.equals("Right")){
                                isValidImgCode = true;
                            }
                        }
                    }
                }
            }
            if(!isValidImgCode){
                // 点击验证码
                click_by_id("imgObj");
            }
            imgIndex++;
        }while (!isValidImgCode && imgIndex<=4)
        hide();
        //检查验证码是否输入正常
        // var captchaInputResult = luaFuncs.checkIfInput("code", captcha);
        logger.info("isValidImgCode 返回信息"+isValidImgCode);
        var isCaptchaInputCorrectFunc = function(isValidImgCode) {
            return isValidImgCode;
        }
        var getCaptchaInputErrorMsgFunc = function() {
            return "图片验证码错误"
        }
        assertTrueOrThrowException(isValidImgCode, isCaptchaInputCorrectFunc, getCaptchaInputErrorMsgFunc);
        // luaFuncs.mouseMoveClick();
        var smsCodeUrl = "https://ebill.spdbccc.com.cn/cloudbank-portal/loginController/sendLoginSms.action";
        var paramsMap = new HashMap();
        paramsMap.put("idNo", idNo);
        paramsMap.put("idType", "01");
        paramsMap.put("yzmM", captcha);
        var isSmsFild = false;
        // 因为短信60秒内不能重复发送，这个不需要进行循环
        logger.info("浦发云账单,任务{} 发送短信验证码请求",context.get(LUA_TASK_KEY));
        var smsCodeHtml = luaFuncs.pf_ajax_post(smsCodeUrl, paramsMap, timeout);
        logger.info("浦发云账单,任务{} 发送短信验证码是否正确,返回结果为：{}",context.get(LUA_TASK_KEY),smsCodeHtml);
        if(smsCodeHtml != undefined){
            if(smsCodeHtml.contains("msg")){
                var smsCodeJsoup = JSON.parse(smsCodeHtml);
                logger.info("浦发云账单 taskKey:{} 发送短信是否成功，smsCodeJsoup:{}",context.get(LUA_TASK_KEY),smsCodeJsoup);
                if(smsCodeJsoup != undefined){
                    var smsCodeRes = smsCodeJsoup.get("msg");
                    if(Boolean.valueOf(smsCodeRes)){
                        isSmsFild = true;
                    }else if(equals("yzm60s",smsCodeRes)){
                        isSmsFild = true;
                    }else{
                        isSmsFild = false;
                    }
                }
            }
        }
        var isSmsSendCorrectFunc = function(isSmsFild) {
            return isSmsFild;
        }
        var getSmsSendErrorMsgFunc = function() {
            return "发送短信失败";
        }
        assertTrueOrThrowException(isSmsFild, isSmsSendCorrectFunc, getSmsSendErrorMsgFunc);
        logger.info("浦发云账单 taskKey:{} 发送短信成功，",context.get(LUA_TASK_KEY));
        showTimes =  System.nanoTime() - showTimes;   //用来计算窗口show的时间
        logger.info("浦发云账单 taskKey:{} 开始等待短信验证码时间{}",context.get(LUA_TASK_KEY),showTimes);
        hide();
        //等待短信
        var smsCode = waitSmsCodeBySeconds(context, 120);
        logger.info("浦发云账单 taskKey:{} 等待短信结果{}",context.get(LUA_TASK_KEY),smsCode);
        //action开始: 校验短信验证码
        var isSmsCodeCorrectFunc = function(smsCode) {
            return StringUtils.isNotBlank(smsCode) && smsCode.length === 6;
        }
        var getSmsCodeErrorMsgFunc = function() {
            return "短信验证码错误";
        }
        assertTrueOrThrowException(smsCode, isSmsCodeCorrectFunc, getSmsCodeErrorMsgFunc);
        showTimes =  System.nanoTime() - showTimes;   //用来计算窗口show的时间
        logger.info("浦发云账单 taskKey:{} 开始等待验证短信验证码结束时间{}",context.get(LUA_TASK_KEY),showTimes);
        //输入短信验证码
        set_input_text_by_id("messagePwd",smsCode);
        //检查短信验证码是否输入正常
        var smsInputResult = luaFuncs.checkIfInput("messagePwd",smsCode);

        var isSmsInputCorrectFunc = function(smsInputResult) {
            return Boolean.valueOf(smsInputResult);
        }

        var getSmsInputErrorMsgFunc = function(smsInputResult) {
            return "短信验证码错误";
        }
        assertTrueOrThrowException(smsInputResult, isSmsInputCorrectFunc, getSmsInputErrorMsgFunc);
        //显示窗口
        luaFuncs.setSizeAndShow();
        luaFuncs.threadSleep();
        //点击登录按钮
        luaFuncs.click_login_button();
        loginHtml = luaFuncs.getHtml2();
        storeDataToFile(context, loginHtml, "loginHtml.html");
        logger.info("浦发云账单 taskKey:{} 登录按钮点击后页面已保存",context.get(LUA_TASK_KEY));
        var doc = Jsoup.parse(loginHtml);
        var isLoginMassge = doc.select("#tipInfo").text();
        var loginFlag = true;
        if(StringUtils.isNotBlank(isLoginMassge)){
            logger.info("浦发云账单 登录信息 tipInfo:{}",isLoginMassge);
            loginFlag=false;
        }
        logger.info("浦发云账单 登录信息 isLoginMassge:{}",isLoginMassge);
        var isLoginCorrectFunc = function() {
            return loginFlag;
        }
        var getLoginErrorMsgFunc = function(loginHtml) {
            if(loginHtml === null) {
                return "短信验证码错误";
            } else if(StringUtils.isNotBlank(isLoginMassge)) {
                return isLoginMassge;
            }
        }
        assertTrueOrThrowException(loginHtml, isLoginCorrectFunc, getLoginErrorMsgFunc);
        hide();
        var accSize = doc.select("#loginAccount option").size() > 1;
        var accMonthSize = doc.select("#loginMonth option").size() > 1;
        logger.info("浦发云账单 taskKey:{} 获取到用户有{} 个账户",context.get(LUA_TASK_KEY),accSize);
        var isLoginCorrectFunc = function(accSize) {
            return accSize;
        }
        var getLoginErrorMsgFunc = function() {
            return "未获取到卡片信息";
        }
        assertTrueOrThrowException(accSize, isLoginCorrectFunc, getLoginErrorMsgFunc);
        //从选择账号，月份页面跳入账单页面
        jumpToBillHtml();

    },
    crawl : crawl,
    exitLogin :function () {}

}

function smsCodeValid() {
    //重新获取图片验证码

    // 输入图片验证码

    // 验证图片验证码是否正确

    // 获取短信验证码

    // 等待输入短信验证码


}

function jumpToBillHtml(){
    var monthIndex = 1;
    var allMonthCount = 12;
    //跳转是否成功的标记
    var jumpNotOk;
    do{
        jumpNotOk = false;
        //查看用户是否有卡列表信息
        luaFuncs.selectAccount();
        screen_print();
        //storeDataToFile(context, selectAccountHtml, "selectAccount.html");
        luaFuncs.selectBillMonth(Integer.parseInt(monthIndex));
        luaFuncs.jumpToBill();

        //判断是否跳转成功
        jumpNotOk = checkIfJumpSuccess(monthIndex);
        screen_print();
        monthIndex++;
    } while(jumpNotOk);
}

function checkIfJumpSuccess(monthIndex){
    var loginHtml2 = luaFuncs.getHtml2();
    storeDataToFile(context, loginHtml2, "loginHtml2_"+monthIndex+".html");
    if(StringUtils.isNotBlank(loginHtml2)){
        var doc = Jsoup.parse(loginHtml2);
        var errorMsg = doc.select("#tipInfo").text();
        logger.info("浦发云账单 taskKey:{} 打印错误提示信息 {}",context.get(LUA_TASK_KEY),errorMsg);
        if(StringUtils.isNotBlank(errorMsg)){
            if(errorMsg.contains("该月账单暂未产生，请选择其他月份！")){
                logger.info("浦发云账单 taskKey:{} 选择第：【{}】个账单月跳转失败,该月账单暂未产生，请选择其他月份！",context.get(LUA_TASK_KEY),monthIndex);
                return true;
            }else if(errorMsg.contains("请选择年月")){
                logger.info("浦发云账单 taskKey:{} 选择第：【{}】个账单月跳转失败,该月账单暂未产生，请选择年月",context.get(LUA_TASK_KEY),monthIndex);
                return true;
            }else if(errorMsg.contains("请选择账户号")){
                luaFuncs.closeErrorMsgButton();
                logger.info("浦发云账单 taskKey:{} 未选择账户号,请选择账户号",context.get(LUA_TASK_KEY));
                return true;
            }else{
                logger.error("浦发云账单 taskKey:{} 检查跳转账单页结果时发现新分支,{}",context.get(LUA_TASK_KEY), errorMsg);
                throw new BankException(BALO_23001_10,"检查跳转账单页结果时发现新分支");
            }
        }else {
            logger.info("浦发云账单 taskKey:{} 跳转到账单详情页面未获取到错误信息，跳转成功！",context.get(LUA_TASK_KEY));
            return false;
        }
    }else {
        logger.info("浦发云账单 taskKey:{} 跳转到账单详情页面为空:{}",context.get(LUA_TASK_KEY),loginHtml2);
        throw new BankException(BALO_23001_10,"跳转到账单详情页面为空");
    }
}

function crawl(){
    logger.info("浦发云账单 taskKey:{} 开始抓取信用卡卡信息",context.get(LUA_TASK_KEY));
    var accountInfoList =  Jsoup.parse(loginHtml).select("#loginAccountHide option");
    // var accountInfoList =  billDetailMap.get("accountInfoList");
    var dataList = new ArrayList();
    //accountInfoList  是从页面中拿下来的卡号的列表，本处对多卡的情况循环抓取
    // if(accountInfoList.length > 0){
    //i 从 1 开始是因为下拉列表的第一个选项不需要解析
    //获取卡号列表信息
    var cardListUrl = "https://ebill.spdbccc.com.cn/cloudbank-portal/loginController/queryAccountList.action";
    var paramsMap = new HashMap();
    var cardListHTML = luaFuncs.pf_ajax_post(cardListUrl, paramsMap, timeout);
    storeDataToFile(context, cardListHTML,"spdCardList.html");
    context.put("cardListHTML",cardListHTML);
    var cardList = new ArrayList();
    var full_card_num = "";
    if(StringUtils.isNotBlank(cardListHTML)){
        if(cardListHTML.contains("9DhefwqGPrzGxEp9hPaoag") || cardListHTML.contains("return is null") || cardListHTML.contains("/images/wl.png")){
            logger.info("浦发云账单 taskKey:{} 未获取用户卡列表信息，",context.get(LUA_TASK_KEY));
        }else{
            var cardListMap = JSON.parse(cardListHTML);
            cardList =  cardListMap.accountInfoList;
            if(cardList != null){
                if (cardList.size()>0){
                    full_card_num = cardList[0].cardNum.trim().replace(/\s/g,"");
                }
            }
        }
    }
    // 有的用户通过上面的请求无法获取到卡号，通过下面的历史账单获取卡号
    if(StringUtils.isBlank(full_card_num)){
        // 通过历史账单获取卡号
        logger.info("浦发云账单 taskKey:{} 通过历史账单获取卡列表信息，",context.get(LUA_TASK_KEY));
        try {
            var historyCardListUrl = "https://ebill.spdbccc.com.cn/cloudbank-portal/historyBillController/getHistorycCardList.action";
            var paramsMap = new HashMap();
            var hisIndex = 1;
            do {
                logger.info("浦发云账单 taskKey:{} 第{}次通过历史账单获取卡号，",context.get(LUA_TASK_KEY),hisIndex);
                var historyCardListHtml= luaFuncs.pf_ajax_post(historyCardListUrl, paramsMap, timeout);
                // 等待三秒钟;
                luaFuncs.threadSleep();
                storeDataToFile(context, historyCardListHtml,hisIndex + "spdHistoryCardList.html");
                hisIndex++;
            }while ((historyCardListHtml.contains("9DhefwqGPrzGxEp9hPaoag") ||
                    historyCardListHtml.contains("return is null") ||
                    historyCardListHtml.contains("/images/topimg.png")) && hisIndex<5);
            if(historyCardListHtml.contains("9DhefwqGPrzGxEp9hPaoag") || historyCardListHtml.contains("return is null") || historyCardListHtml.contains("/images/topimg.png")){
                logger.info("浦发云账单 taskKey:{} 通过历史账单获取卡号方法未获取用户卡列表信息，",context.get(LUA_TASK_KEY));
            }else{
                var historyCardListMap = JSON.parse(historyCardListHtml);
                full_card_num =  historyCardListMap.defaultCard.trim().replace(/\s/g,"");
            }
        }catch (e) {
            logger.info("浦发云账单 taskKey:{} 通过历史账单获取卡号方法,报错，{}",context.get(LUA_TASK_KEY),e);
            statCaughtException(context, e);
        }
    }
    for (var i=1; i<accountInfoList.size(); i++){
        logger.info("浦发云账单 taskKey:{} 开始抓取第：{} 张卡信息",context.get(LUA_TASK_KEY),i+1);
        var option = accountInfoList[i];
        indexOfCard++;
        var creditCardAllData = new CreditCardAllData();
        if(StringUtils.isNotBlank(full_card_num)){
            creditCardAllData.setFullCardNum(full_card_num);
            creditCardAllData.setCardNum(full_card_num.substring(full_card_num.length() - 4));
        }
        dataList.add(creditCardAllData);
        //获取客户号
        // var accountId = option.get("account").trim();//去除所有空格
        parseAccountAndBillDay(option);
        //保存基本信息
        //setAccountInfo(data, option);

        //获取账单，账单详情数据
        setDoneAndUnDoneBillAndDetailData(account, creditCardAllData);
    }
    context.put(Constants.CREDIT_DATA, dataList);

}

//解析本卡的账单日和客户号
function parseAccountAndBillDay(option){
    if(null == option){
        logger.error("浦发云账单 taskKey:{} 解析账户号，账单日发生异常：",context.get(LUA_TASK_KEY),e);
        throw new BankException(BALO_99601_40 ,"解析账户号，账单日发生异常");
    }
    billDay = option.attr("value");
    logger.info("浦发云账单 taskKey:{} 获取到账单日为：{}", context.get(LUA_TASK_KEY), billDay);
    account = option.text();
    logger.info("浦发云账单 taskKey:{} 获取到客户号为：{}", context.get(LUA_TASK_KEY), account);

    if(null == billDay || null == account){
        logger.error("浦发云账单 taskKey:{} 解析账户号，账单日发生异常：",context.get(LUA_TASK_KEY),e);
        throw new BankException(BALO_99601_40 ,"解析账户号，账单日发生异常");
    }
}



/**
 * 已出账单，未出账单表头，及详情的获取（循环十二个月抓取）
 * @param accountMap
 * @param creditCardAllData
 */
function setDoneAndUnDoneBillAndDetailData(accountId, creditCardAllData){

    var monthList = getTwelveMonth(billDay);
    try {
        for(var i=0; i<monthList.size(); i++){
            var billMonth = monthList.get(i);
            logger.info("浦发云账单 taskKey:{} 现在开始【{}】月账单的抓取",context.get(LUA_TASK_KEY),billMonth);
            getDoneAndUnBillTitle(accountId, creditCardAllData, billMonth, i);

        }
        // 获取未出账单信息

    } catch (e) {
        logger.error("浦发云账单 taskKey:{} 抓取已出未出账单时异常：",context.get(LUA_TASK_KEY), e);
        statCaughtException(context, e);
    }
}



/**
 * 获取该月月账单表头信息
 */
function getDoneAndUnBillTitle( accountId,  creditCardAllData,  billMonth, monthIndex){

    try {

        var showPcIndexUrl = "" ;
        var askBillHtmlUrl = "https://ebill.spdbccc.com.cn/cloudbank-portal/loginController/loginIndex.action?accountId="+ accountId +"&billYM="+ billMonth;

        //循环抓取月份信息时，第一个月的请求跟其余月的请求稍有不同（请求参数不同,链接不同）故分开处理
        if(0 == monthIndex){
            logger.info("浦发云账单 taskKey:{} 第一个月账单信息请求即将发送",context.get(LUA_TASK_KEY));
            var billHtml = luaFuncs.pf_ajax_get(askBillHtmlUrl, timeout);
            storeDataToFile(context, billHtml, indexOfCard + "_"+"billHtml.html");
            if(billHtml.contains("return is null")){
                logger.info("浦发云账单 taskKey:{} ：第一个月账单页面响应为空",context.get(LUA_TASK_KEY),billMonth);
            }
        }else{
            var changeAccountOrBillDataUrl = "https://ebill.spdbccc.com.cn/cloudbank-portal/myBillController/changeAccountOrBillData.action";

            var paramsMap = new HashMap();
            paramsMap.put("bilM", billMonth);
            paramsMap.put("accountId", accountId);

            var changeAccountOrBillDataHtml =luaFuncs.pf_ajax_post(changeAccountOrBillDataUrl, paramsMap, timeout);
            //辅助请求就是本请求可能不需要拿回数据，但是不发它接下来的请求会出错
            logger.info("浦发云账单，taskKey:{} 查询非第一个月的月账单表头时的辅助请求changeAccountOrBillDataUrl 已经发送！",context.get(LUA_TASK_KEY));
            storeDataToFile(context, changeAccountOrBillDataHtml, indexOfCard+"_changeAccountOrBillDataHtml_"+billMonth+".html");
            if(!changeAccountOrBillDataHtml.contains("flag")){
                return;
            }
            showPcIndexUrl = "https://ebill.spdbccc.com.cn/cloudbank-portal/myBillController/showPcIndex.action";

            var showPcIndexHtml = luaFuncs.pf_ajax_get(showPcIndexUrl, timeout);
            logger.info("浦发云账单，taskKey:{} 查询非第一个月的月账单表头时的辅助请求showPcIndexUrl 已经发送！",context.get(LUA_TASK_KEY));
            storeDataToFile(context, showPcIndexHtml, indexOfCard+"_showPcIndexHtml_"+billMonth+".html");
        }
        //再发送一个请求，获取主页面的数据
        var loadHomeDataUrl = "https://ebill.spdbccc.com.cn/cloudbank-portal/myBillController/loadHomeData.action";
        var billDataHtml = luaFuncs.pf_ajax_get(loadHomeDataUrl,timeout);
        logger.info("浦发云账单，taskKey:{},月账单：{}主页面获取到即将保存！",context.get(LUA_TASK_KEY), billMonth);
        storeDataToFile(context, billDataHtml, indexOfCard + "_" + billMonth + "_DoneBill.html");
        if(StringUtils.isBlank(billDataHtml)){
            logger.info("浦发云账单，taskKey:{},月账单：{}主页为空",context.get(LUA_TASK_KEY),billMonth);
            throw new BankException(BALO_99601_40, "抓取月账单表头所需参数未获取到");
        }else if (billDataHtml.contains("Unable to process requested URL") || billDataHtml.contains("cross-domain fail")){
            logger.info("浦发云账单，taskKey:{},月账单：{}主页提示：Unable to process requested URL",context.get(LUA_TASK_KEY),billMonth);
            throw new BankException(BALO_21301_10, "Unable to process requested URL");
        }else if (billDataHtml.contains("return is null") ){
            logger.info("浦发云账单 taskKey:{} 月份：{} 主页返回为return is null",context.get(LUA_TASK_KEY),billMonth);
        }else if (billDataHtml.contains("9DhefwqGPrzGxEp9hPaoag") ){
            logger.info("浦发云账单 taskKey:{} 月份：{} 主页返回为页面元素中包含'9DhefwqGPrzGxEp9hPaoag'的空白页面",context.get(LUA_TASK_KEY),billMonth);
        }else if(StringUtils.isNotBlank(billDataHtml)){
            //该请求是为接下来的账单详情做准备
            var preBillDetailDataUrl = "https://ebill.spdbccc.com.cn/cloudbank-portal/billDetailController/PCbillDetail.action";
            var preBillDetailDataHtml = luaFuncs.pf_ajax_get(preBillDetailDataUrl,timeout);
            if(!equals("",preBillDetailDataHtml) && null !== preBillDetailDataHtml){
                var undoneBill = new BillAllData();
                var bill = new BillAllData();
                //解析月账单表头
                parseBillData(billDataHtml, creditCardAllData, bill, undoneBill, billMonth);
                if(0 == monthIndex){
                    creditCardAllData.getBills().add(undoneBill);
                    //解析未出账单详情
                    logger.info("浦发云账单 taskKey:{} 即将抓取未出账单",context.get(LUA_TASK_KEY));
                    parseUndoneBillDetail(undoneBill);
                }
                //解析账单详情
                parseDoneBillDetail(bill,billMonth);
                //当请求月账单详情时，页面顶端的月账单表头详情信息的获取
                getBillInfo(bill, undoneBill);
                //如果本月有未出账单 new 一个 BillAllData --- 也就是本月的未出账单和本月的已出账单用同一个表头(不同对象，相同值)
                creditCardAllData.getBills().add(bill);
            }else{
                logger.info("浦发云账单，taskKey:{},{}月账单详情，preBillDetailDataHtml 未获取到响应页面",context.get(LUA_TASK_KEY), billMonth);
                throw new BankException(BACR_20306_30,"消费明细获取失败");
            }
        }else{
            logger.info("浦发云账单 taskKey:{} 获取月账单时发生异常：{}", context.get(LUA_TASK_KEY), billDataHtml)
            throw new BankException(BACR_99601_60,errorMsgMap.get(BACR_99601_60));
        }

    } catch (e) {
        logger.error("浦发信用卡云账单 taskKey:{} getDoneAndUnBillTitle  方法发生异常：{}",context.get(LUA_TASK_KEY),e);
        statCaughtException(context, e);
    }
}

/**
 * 本请求时在请求账单详情时同时获取的月账单的消费数据   本期应还款总额= 上期应还款余额- 已还款金额/其他入账+ 新签金额/其他费用
 * @param bill
 */
function getBillInfo(bill, newBill){

    var PCloadHomeDataUrl = "https://ebill.spdbccc.com.cn/cloudbank-portal/billDetailController/PCloadHomeData.action";

    //var PCloadHomeDataHtml = ajax_get(PCloadHomeDataUrl);
    var PCloadHomeDataHtml = luaFuncs.pf_ajax_get(PCloadHomeDataUrl,timeout);
    logger.info("浦发云账单，taskKey:{},{} 月账单 PCloadHomeData请求已经发送。",context.get(LUA_TASK_KEY), bill.getBillMonth());
    storeDataToFile(context, PCloadHomeDataHtml, indexOfCard + "_PCloadHomeData_"+bill.getBillMonth()+".html");
    //9DhefwqGPrzGxEp9hPaoag此字符是空白页面时，页面包含元素
    if(PCloadHomeDataHtml.contains("Unable to process requested URL")|| PCloadHomeDataHtml.contains("return is null") || PCloadHomeDataHtml.contains("9DhefwqGPrzGxEp9hPaoag")){
        logger.info("浦发云账单，taskKey:{},{} 月账单 PCloadHomeData请求响应提示：未获取到数据直接退出",context.get(LUA_TASK_KEY), bill.getBillMonth());
        return;
    }

    try {
        var PCloadHomeData = JSON.parse(PCloadHomeDataHtml);
        if(null == PCloadHomeData || PCloadHomeData.size() <= 0 ){
            logger.info("浦发云账单，taskKey:{},{} 月账单 PCloadHomeData请求响应为空",context.get(LUA_TASK_KEY), bill.getBillMonth());
        }else{
            //解析
            var billData = PCloadHomeData.billData;
            var last_payments = billData.backMoney;   //已还款金额
            last_payments = ifNullSet0(last_payments);
            bill.setLastPayment(new BigDecimal(last_payments).multiply(new BigDecimal(-1)));//把已还金额设置为负数
            newBill.setLastPayment(null);

            var new_balance = billData.cash;          //本期应还总额
            new_balance = ifNullSet0(new_balance);
            bill.setNewBalance(new BigDecimal(new_balance));

            var last_balance = billData.lastMoney;    //上期应还款余额
            last_balance = ifNullSet0(last_balance);
            bill.setLastBalance(new BigDecimal(last_balance));
            newBill.setLastBalance(new BigDecimal(last_balance));

            var new_balance_undone = newBill.getNewBalance();
            if(null == new_balance_undone || equals("",new_balance_undone)){
                new_balance_undone = new BigDecimal(0);
            }
            newBill.setNewBalance(new BigDecimal(last_balance).add(new_balance_undone));

            //本期应还款总额 - 上期应还款余额  + 已还款金额/其他入账 = 新签金额/其他费用
            var new_charges = new BigDecimal(new_balance).add(new BigDecimal(last_payments)).subtract(new BigDecimal(last_balance));
            bill.setNewCharges(new_charges);
        }

    } catch (e) {
        logger.error("浦发信用卡云账单 taskKey:{} getBillInfo  方法发生异常：{}",context.get(LUA_TASK_KEY),e);
        statCaughtException(context, e);
    }

}

/**
 * 几个金额字段，如果从页面取下值为 null 那么为其赋值为 0
 */
function ifNullSet0(amount){
    if(null == amount || equals("",amount) || typeof amount == "undefined"){
        amount = "0";
    }else{
        amount = amount.trim().replaceAll(",", "").replaceAll("￥", "");
    }
    return amount;
}

/**
 * 解析月账单的表头数据
 * @param billDataHtml
 * @param data
 */
function parseBillData(billDataHtml, data, bill, newBill, billMonth){

    //美元相关
    setValueForBillUSDCredit(newBill);
    newBill.setInterest(null);
    newBill.setBillId(UUID.randomUUID().toString());
    newBill.setBankName("浦发银行");
    //美元相关
    setValueForBillUSDCredit(bill);
    bill.setInterest(null);
    bill.setBillId(UUID.randomUUID().toString());
    bill.setBankName("浦发银行");
    try {
        if(billDataHtml.contains("return is null")){
            logger.error("浦发云账单 taskKey:{} 月份：{} billDataHtml页面响应为空",context.get(LUA_TASK_KEY),billMonth);
        }else{
            //在月账单中为data中的几个字段赋值
            parseAccountDetailInfo(billDataHtml, data);
            var map = JSON.parse(billDataHtml);
            var userName = map.userName;
            //持卡人姓名
            userName = userName.replaceAll(" ","").replaceAll("先生","").replaceAll("女士","");
            data.setNameOnCard(userName);
            //预借现金额度
            var cash_limit = map.cashLimit.replaceAll("￥", "").replaceAll(",", "").trim();    //￥47,500.00
            data.setCashLimit(new BigDecimal(cash_limit));

            // 还款日
            var date = map.lastBackDate;
            if(null !== date && !equals("",date)){
                var payment_due_date = TimeUtil.getTimeStr(TimeUtil.getTime(date, "yyyyMMdd"),"yyyy-MM-dd");
                bill.setPaymentDueDate(yyyy_MM_dd_PARSER.parse(payment_due_date));
            }
            // 账单日
            var billMonth1 = map.billMonth;  //201712
            billDay = map.accDay;
            var date1 = billMonth1 + String.valueOf(billDay);
            if(null !== date1 && !equals("",date1)){
                var bill_date = TimeUtil.getTimeStr(TimeUtil.getTime(date1, "yyyyMMdd"),"yyyy-MM-dd");
                bill.setBillDate(yyyy_MM_dd_PARSER.parse(bill_date));//账单日
                newBill.setBillDate(yyyy_MM_dd_PARSER.parse(changeBillMonth(bill_date)));
            }
            //账单月份
            var date2 = map.billMonth;
            if(null !== date2 && !equals("",date2)){
                var bill_month1 = TimeUtil.getTimeStr(TimeUtil.getTime(date2, "yyyyMM"),"yyyy-MM");
                bill.setBillMonth(bill_month1);//账单月份
                newBill.setBillMonth(changeBillMonth(bill_month1));
            }
            //本期账单金额
            var new_balance = map.cash.replaceAll(",", "").trim();
            if(null !== new_balance && !equals("",new_balance)){
                bill.setNewBalance(new BigDecimal(new_balance));
            }
            //最低还款额
            var min_payment = map.minPay.replaceAll(",", "").trim();
            if(null !== min_payment && !equals("",min_payment)){
                bill.setMinPayment(new BigDecimal(min_payment));
                newBill.setMinPayment(null);
            }
            //信用卡额度
            var credit_limit = map.creditLimit.replaceAll(",", "").replaceAll("￥", "").trim();
            if(null !== credit_limit && !equals("",credit_limit)){
                bill.setCreditLimit(new BigDecimal(credit_limit));
                newBill.setCreditLimit(new BigDecimal(credit_limit));
            }
            bill.setCashLimit(new BigDecimal(cash_limit));
            newBill.setCashLimit(new BigDecimal(cash_limit));
        }

    } catch (e) {
        logger.info("浦发云账单，taskKey:{} parseBillData()方法 月份：{} 发生异常：{}",context.get(LUA_TASK_KEY),billMonth , e);
        statCaughtException(context, e);
    }

}

//在月账单中为data中的几个字段赋值
function parseAccountDetailInfo(billDataHtml, data){
    try {

        data.setCardId(UUID.randomUUID().toString());
        data.setCardType("信用卡");
        data.setBankName("浦发银行");
        data.setCashBalance(null);

        if(StringUtils.isNotBlank(billDataHtml)){
            var billData = JSON.parse(billDataHtml);
            var credit_limit = billData.creditLimit.trim().replaceAll(",","").replaceAll("￥","");
            data.setCreditLimit(new BigDecimal(credit_limit));
            var balance = billData.creditLimit.trim().replaceAll(",","").replaceAll("￥","");
            data.setBalance(new BigDecimal(balance));
            // var full_card_num = billData.cardNo.trim().replace(/\s/g,"");//去除所有空格   张振伟修改
            // data.setFullCardNum(full_card_num);
            // data.setCardNum(full_card_num.substring(full_card_num.length() - 4));
        }
    } catch (e) {
        logger.error("浦发云账单 taskKey:{} parseAccountDetailInfo()方法中解析基本信息异常：{}",context.get(LUA_TASK_KEY),e);
        statCaughtException(context, e);
    }
}

function parseUndoneBillDetail(bill){
    bill.setBillType("UNDONE");

    //请求未出账单详情
    var unDoneBillDetailUrl = "https://ebill.spdbccc.com.cn/cloudbank-portal/billDetailController/showPCUnBillDetail.action";
    var unDoneBillDetail = luaFuncs.pf_ajax_get(unDoneBillDetailUrl,timeout);
    logger.info("浦发云账单，taskKey:{},获取到：{}月，未出账单详情",context.get(LUA_TASK_KEY));
    storeDataToFile(context, unDoneBillDetail, indexOfCard +"_"+ "_UNDONE_bill_shopping.html");

    if(StringUtils.isNotBlank(unDoneBillDetail) && !unDoneBillDetail.contains("return is null") ){
        var billDetailMap = JSON.parse(unDoneBillDetail);
        if(billDetailMap.size() > 0){
            var listDate = billDetailMap.get("billDetaillist");
            var list = listDate.get("billDataList");
            logger.info("浦发云账单，list:{},", list);
            if(null !== list && list.size() > 0){
                var installmentList = new ArrayList();
                var orderIndex = 0;
                //logger.info("浦发云账单，taskKey:{},获取到：{}月,获取到的数据为billDetaillist:{}，未出账单详情",context.get(LUA_TASK_KEY), list.get(0));
                for each(var map in list){
                    orderIndex++;
                    getExpense(map, bill, "UNDONE", orderIndex,installmentList);
                }
                manageInstallmentList(installmentList);
                bill.setInstallments(installmentList);
            }
        }
    }else{
        logger.error("浦发云账单， taskKey:{} 获取到：{}月，未出账单详情 为空 ----网络异常 ",context.get(LUA_TASK_KEY), bill.getBillMonth());
    }

}


/**
 * 解析账单详情
 *
 */
function parseDoneBillDetail(bill,billMonth){
    bill.setBillType("DONE");
    //请求账单详情
    var billDetailUrl = "https://ebill.spdbccc.com.cn/cloudbank-portal/billDetailController/PCloadBillsDetailAll.action";

    var paramsMap = new HashMap();
    paramsMap.put("month", "$month");
    paramsMap.put("rnd", Double.toString(Math.random()));
    paramsMap.put("sort", "0");
    //如果出现网络异常原因，请求反复调用3次
    var billDetailHtml = "";
    do{
        billDetailHtml= luaFuncs.pf_ajax_post(billDetailUrl, paramsMap, timeout);
        billIndex++
    }while (billDetailHtml.contains("images/wl.png") && billIndex < 4)
    // var billDetailHtml = RequestUtil.post(billDetailUrl, paramsMap, header);
    //var billDetailHtml = luaFuncs.pf_ajax_post(billDetailUrl, paramsMap, timeout);
    logger.info("浦发云账单，taskKey:{},获取到：{}月，账单详情",context.get(LUA_TASK_KEY), billMonth);
    storeDataToFile(context, billDetailHtml, indexOfCard +"_"+ "bill_Done_"+billMonth+"_shopping.html");
    if(billDetailHtml.length() > 0 && !billDetailHtml.contains("return is null") && !billDetailHtml.contains("images/wl.png") && !StringUtils.equals(billDetailHtml,"") && !billDetailHtml.contains("9DhefwqGPrzGxEp9hPaoag")){
        var billDetailMap = JSON.parse(billDetailHtml);
        if(billDetailMap.size() > 0){
            var listDate = billDetailMap.get("billDataList");
            // logger.info("浦发云账单，listDate:{},", listDate);
            var list = listDate.get("billDataList");
            // logger.info("浦发云账单，list:{},", list);
            if(null !== list && list.size() > 0){
                var installmentList = new ArrayList();
                var orderIndex = 0;
                for each(var map in list){
                    orderIndex++;
                    getExpense(map, bill, "DONE", orderIndex,installmentList);
                }
                manageInstallmentList(installmentList);
                bill.setInstallments(installmentList);
            }
        }
    }else{
        logger.error("浦发云账单，taskKey:{},获取到：{}月，账单详情页面为空----网络错误",context.get(LUA_TASK_KEY), bill.getBillMonth())
    }

}

/**
 * 保存消费详情
 * @param map
 * @param bill
 * @param billType   --unDone  or done
 */
function getExpense(map, bill, billType, orderIndex,installmentList){
    try {
        var expense = new Expense();
        bill.getShoppingSheets().add(expense);
        var uuid = UUID.randomUUID().toString()
        expense.setId(uuid);
        expense.setBalance(null);
        expense.setCurrencyType("CNY");
        expense.setOrderIndex(orderIndex);

        //页面上  cardNbr1 参数为卡号
        var full_card_num = map.cardNbr1;
        expense.setCardNum(full_card_num.substring(full_card_num.length()-4));
        //页面上将本条消费详情的描述分为两部分表示 desLine1 和 desLine2 我们需要将他们组合起来作为我们的描述字段
        var description = map.desLine1;
        var description1 = map.desLine2;
        if(!equals("",description1)){
            description = description+description1;
        }
        expense.setDescription(description);
        var valDate = map.valDate;
        expense.setPostDate(yyyy_MM_dd_PARSER.parse(TimeUtil.getTimeStr(TimeUtil.getTime(valDate, "yyyyMMdd"), "yyyy-MM-dd")));
        var purDate8 = map.purDate8;
        expense.setTransDate(yyyy_MM_dd_HH_mm_ss_PARSER.parse(TimeUtil.getTimeStr(TimeUtil.getTime(purDate8, "yyyyMMdd"),"yyyy-MM-dd HH:mm:ss")));

        var cunOrQu = map.amountFl;
        var amountMoney = map.amount.replaceAll(",", "").trim();
        amountMoney = StringToBigDecimal(amountMoney);
        if(equals("DONE",billType)){
            if(equals("C",cunOrQu)){
                expense.setAmountMoney(amountMoney.multiply(new BigDecimal("-1")));
            }else if(equals("D",cunOrQu)){
                expense.setAmountMoney(amountMoney);
            }
        }else if(equals("UNDONE",billType)){
            if(equals("-",cunOrQu)){
                expense.setAmountMoney(amountMoney.multiply(new BigDecimal("-1")));

                var new_balance = bill.getNewBalance();
                logger.info("new_balance = " + context.get(LUA_TASK_KEY) +" "+ new_balance);
                logger.info("null == new_balance  ？:{}" , (new_balance == null || equals("",new_balance)));
                if(new_balance == null  || equals("",new_balance)){
                    new_balance = new BigDecimal("0");
                }else if(new_balance == undefined){
                    new_balance = new BigDecimal("0");
                }
                logger.info("new_balance = " + context.get(LUA_TASK_KEY) +" "+ new_balance);
                bill.setNewBalance(new_balance.add(amountMoney.multiply(new BigDecimal("-1"))));//本期账单金额

            }else if(equals("+",cunOrQu)){
                expense.setAmountMoney(amountMoney);
                var new_balance = bill.getNewBalance();
                if(new_balance == null || equals("",new_balance)){
                    new_balance = new BigDecimal("0");
                }else if(new_balance == undefined){
                    new_balance = new BigDecimal("0");
                }
                bill.setNewBalance(new_balance.add(amountMoney));

                var new_charges = bill.getNewCharges();
                if(new_charges == null  || equals("",new_charges)){
                    new_charges = new BigDecimal("0");
                }else if(new_charges == undefined){
                    new_charges = new BigDecimal("0");
                }
                bill.setNewCharges(new_charges.add(amountMoney));//本期新增款额
            }
        }
        // expense.setCategory(installmentTypeChange(description));
        if(description.contains("第")&&description.contains("期")&&description.contains("共")){
            expense.setCategory("INSTALLMENT");
        }else if(description.contains("消费")){
            expense.setCategory("SHOPPING");
        }else if(description.contains("转分期付款")){
            expense.setCategory("PAYMENTS");
        }else{
            expense.setCategory(CategoryUtil.getCreditCategory("SPD", description, amountMoney));
        }

        //处理账单分期数据
        if((description.contains("第") && description.contains("期共")) || description.contains("分期")){
            var installment = new Installment();
            // bill.getInstallments().add(installment);
            installment.setBillId(UUID.randomUUID().toString());
            installment.setAmountMoney(expense.getAmountMoney());
            installment.setCurrencyType(expense.getCurrencyType());
            installment.setInstallmentDesc(description);
            installment.setShoppingsheetId(uuid);
            //这里需要对description进行截取，当description包含现金分期，以前的方法会报错
            var descText = description.substring(description.indexOf("第"),description.length());
            if(!"".equals(descText)){
                var current_month = descText.substring(descText.indexOf("第") + 1, descText.indexOf("期"));
                var total_month = descText.substring(descText.indexOf("共") + 1, descText.lastIndexOf("期"));
                var transDate = getTimeMonthToNumMonth(Integer.toString(current_month),valDate);
                installment.setTransDate(transDate);// 交易日期
                var purDates = getTimeMonthToNumMonth(0,purDate8);//记账日期
                installment.setPostDate(purDates);
                installment.setInstallmentType(expense.getCategory());
                installment.setCurrentMonth(current_month);//当前期数
                installment.setTotalMonth(total_month);//总共期数
            }
            installmentList.add(installment);
        }
        //账单详情中摘取出分期数据
        // getInstallmentsFromExpense( expense, bill);

    } catch (e) {
        logger.info("浦发云账单taskKey:{} 在解析 {}月{}账单数据时出错",context.get(LUA_TASK_KEY),bill.getBillMonth(),billType);
        logger.error(e);
        //statCaughtException(context, e);
    }
}
function inputIdCard(idNo) {
    //输入身份证号
    if(StringUtils.isNotBlank(idNo)){
        var isInputIdNo = set_input_text_by_id("idNo",idNo);
        logger.info("任务【 {} 】验证身份号:{},是否输入:{}",context.get(LUA_TASK_KEY),idNo, isInputIdNo);
        if(equals(isInputIdNo.toLowerCase(),"ok")){
            isInput = true;
        }
    }
    // var idNoInputResult = luaFuncs.checkIfInput("idNo",idNo);
    var isIdNoInputCorrectFunc = function(isInput) {
        return isInput;
    }
    var getIdNoInputErrorMsgFunc = function() {
        return "身份证号未输入";
    }
    assertTrueOrThrowException(isInput, isIdNoInputCorrectFunc, getIdNoInputErrorMsgFunc);
    logger.info("任务【 {} 】身份证号输入成功", context.get(LUA_TASK_KEY));
}

/**
 * 获取图片验证码
 */
function getImgValidCode() {
    //获取图片验证码路径
    var captchaPath = get_image_by_id("imgObj");
    logger.info("任务【 {} 】图片验证码路径【 {} 】", context.get(LUA_TASK_KEY), captchaPath);
    var captchaPathState = true;
    if(captchaPath == null && typeof captchaPath == 'undefined' && captchaPath == 'path fail'){
        captchaPathState = false;
    }
    var isCaptchaPathCorrectFunc = function(captchaPathState) {
        return captchaPathState
    }
    var getCaptchaPathErrorMsgFunc = function() {
        return "图片验证码获取失败"
    }
    assertTrueOrThrowException(captchaPath, isCaptchaPathCorrectFunc, getCaptchaPathErrorMsgFunc)
    logger.info("任务【 {} 】图片验证码获取成功", context.get(LUA_TASK_KEY))
    //识别图片验证码
    context.put(TASK_IMG_PATH, captchaPath);
}
/**
 * 输入图片验证码
 */
function inputImgValidCode() {
//图片验证码只会是4位，但是由于官网返回经常有看不清的字母所以本处支持3,4位
    context.put(TASK_IMG_REGEX,"[0-9a-zA-Z]{4}");
    var captcha = waitImgCodeBySecondsByJs(context,60,true,3);
    logger.info("图片验证码为：{}",captcha);
    if (StringUtils.isBlank(captcha) || captcha.length() < 4) {
        logger.info("浦发云账单 任务taskKey:{} 验证码信息：打码位数不足四位，手动补足 {}", context.get(LUA_TASK_KEY),captcha);
        captcha = "1234";
    }
    //输入图片验证码
    set_input_text_by_id("code", captcha);
    return captcha;
}

/**
 * 账单详情中摘取出分期数据
 * @param expense
 * @param billAllData
 */
function getInstallmentsFromExpense(expense, billAllData) {
    try {
        var remark = expense.getDescription();
        //&& (remark.contains("分期") ||remark.contains("支付网关分") || remark.contains("万用金"))
        if (null !== remark && !equals("", remark) && remark.contains("第") && remark.contains("共") && remark.contains("期") && checkIfContainsNum(remark)) {
            //账单分期 每月分摊本金 (第6期共6期)   账单分期 每月分摊本金 &#40;第3期共6期
            //账单分期 手续费 &#40;第3期共6期      分期付款手续费 支付网关分24期 (第23期共24期)
            logger.info("taskKey:{}  remark = {} ", context.get(LUA_TASK_KEY), remark);
            var remarkStr1 = remark.substring(remark.indexOf("第")); //第3期共6期
            logger.info("taskKey:{}  remarkStr1 = {} ", context.get(LUA_TASK_KEY), remarkStr1);
            var current_month = remarkStr1.substring(remarkStr1.indexOf("第") + 1, remarkStr1.indexOf("期"));
            if (current_month.contains("第")) {
                logger.info("taskKey:{}  current_month = {} ", context.get(LUA_TASK_KEY), current_month);
                current_month = current_month.substring(current_month.indexOf("第") + 1);
            }
            var remarkStr2 = remark.substring(remark.indexOf("共"));
            logger.info("taskKey:{}  remarkStr2 = {} ", context.get(LUA_TASK_KEY), remarkStr2);
            var total_month = remarkStr2.substring(remarkStr2.indexOf("共") + 1, remarkStr2.indexOf("期"));
            var insList = billAllData.getInstallments();
            var ins = null;
            for each(var singleIns in insList){
                var desc = singleIns.getInstallmentDesc();
                var feeDesc = singleIns.getHandingfeeDesc();
                if ((!equals("", desc) && (null !== desc))|| (!equals("", feeDesc) && (null !== feeDesc))) {
                    if (!equals("", feeDesc) && (null !== feeDesc )) {
                        desc = feeDesc;
                    }
                    logger.info("taskKey:{}  desc = {} ", context.get(LUA_TASK_KEY), desc);
                    var sameDesc = equals(desc.substring(0, 3), remark.substring(0, 3));
                    var desc1 = desc.substring(0, 2);
                    var desc2 = remark.substring(0, 2);
                    var condition = false;
                    if ((equals("每月", desc1) && equals("利息", desc2)) || (equals("每月", desc2) && equals("利息", desc1))) {
                        condition = true;
                    }
                    if (current_month == singleIns.getCurrentMonth() && total_month == singleIns.getTotalMonth() && (sameDesc || condition)) {
                        ins = singleIns;
                    }
                }
            }
            if (null == ins) {
                ins = new Installment();
                ins.setBillId(UUID.randomUUID().toString());
                ins.setHandingFee(null);
                ins.setTransferFee(null);
                billAllData.getInstallments().add(ins);
            }
            //remark.contains("本金")||(remark.contains("支付网关分") && remark.contains("手续费")==false)
            if (remark.contains("手续费") == false && remark.contains("利息") == false) {
                ins.setShoppingsheetId(expense.getId());
                ins.setTransDate(expense.getTransDate());
                ins.setPostDate(expense.getPostDate());
                var installment_type = "";
                if (remark.contains("账单")) {
                    installment_type = "BILL";
                } else if (remark.contains("自由")) {
                    installment_type = "CONSUME";
                } else if (remark.contains("自动")) {
                    installment_type = "CONSUME";
                } else if (remark.contains("现金") || remark.contains("万用金")) {
                    installment_type = "CASH";
                } else {
                    installment_type = "CONSUME";
                }
                ins.setInstallmentType(installment_type);
                ins.setCurrentMonth(current_month);
                ins.setTotalMonth(total_month);
                ins.setCurrencyType(expense.getCurrencyType());
                ins.setAmountMoney(expense.getAmountMoney());
                ins.setInstallmentDesc(remark);

            } else if (remark.contains("手续费") || remark.contains("利息")) {
                var installment_type = "";
                if (remark.contains("账单")) {
                    installment_type = "BILL";
                } else if (remark.contains("自由")) {
                    installment_type = "CONSUME";
                } else if (remark.contains("自动")) {
                    installment_type = "CONSUME";
                } else if (remark.contains("现金") || remark.contains("万用金")) {
                    installment_type = "CASH";
                } else {
                    installment_type = "CONSUME";
                }
                ins.setInstallmentType(installment_type);
                ins.setHandingFee(expense.getAmountMoney()); //本期手续费
                ins.setHandingfeeDesc(remark); //分期手续费描述
                ins.setCurrentMonth(current_month);
                ins.setTotalMonth(total_month);
                ins.setCurrencyType(expense.getCurrencyType());
            }

        }
    } catch (e) {
        logger.error("浦发云账单 taskKey :{} getInstallmentsFromExpense 发生异常:{} ", context.get(LUA_TASK_KEY), e)
        statCaughtException(context, e);
    }

}

/**
 * 判断字符串中是否包含字母 （用于判断分期数据的条件中）
 * @param str
 * @return
 */
function checkIfContainsNum(str) {
    var isDigit = false;
    if(str.matches(".*\\d+.*")){
        isDigit = true;
    }
    return isDigit;
}
/**
 * 管理分期，把手续费或息费合并到分期账单中
 * @param installmentList
 */
function manageInstallmentList(installmentList) {
    // 遍历分期数据
    for(var insIndex = 0 ;insIndex < installmentList.size();insIndex++){
        var insInfo = installmentList.get(insIndex);
        var insInfoDesc = insInfo.getInstallmentDesc();
        if(insInfoDesc.contains("息费") || insInfoDesc.contains("手续费")){
            if(installmentList.size() > 0){
                for(var installIndex = 0;installIndex < installmentList.size();installIndex++){
                    var installInfo = installmentList.get(installIndex);
                    var installment_desc = installInfo.getInstallmentDesc();
                    var installmentDescText = installment_desc.substring(installment_desc.indexOf("第"),installment_desc.length());
                    // var install_currentMonth = installInfo.getCurrentMonth();
                    if (insInfoDesc.contains(installmentDescText)){
                        installInfo.setHandingfeeDesc(insInfoDesc);
                        installInfo.setHandingFee(insInfo.getAmountMoney());
                    }
                }
            }
            installmentList.remove(insIndex);
        }
    }
}
/**
 *  获取前后N各月的当天时间
 * @param num 前后几个月
 * @param time 需要转换的时间
 * @returns {*}
 */
function getTimeMonthToNumMonth(num, time) {
    var calendar=Calendar.getInstance()
    // var df=new SimpleDateFormat("yyyyMMdd");
    var years = time.substring(0,4);
    var month = time.substring(4,6);
    var day = time.substring(6,8);
    calendar.set(years, month, day);
    calendar.set(Calendar.MONTH,month-1-num);//默认1月为0月
    var nowTime = calendar.getTime();
    return nowTime;
}
/**
 * 获取查询日期  格式 201705 （年月） 十二个月，包含本月
 */
function getTwelveMonth(billDay ) {

    var now = new Date().getDate();
    now = Integer.parseInt(now);
    if(now < 10){
        now = '0' + now;
    }

    var lst = new ArrayList();
    var calendar = new GregorianCalendar();
    var dfdate = new SimpleDateFormat("yyyyMM");

    if(billDay < now){
        for(var i = 0; i < 12; i++){
            calendar.setTime(new Date());
            calendar.add(Calendar.MONTH, -1 * i);
            lst.add(dfdate.format(calendar.getTime()));
        }
    }else{
        for (var i = 1; i < 13; i++) {
            calendar.setTime(new Date());
            calendar.add(Calendar.MONTH, -1 * i);
            lst.add(dfdate.format(calendar.getTime()));
        }
    }
    return lst;
}

function changeBillMonth(billMonthOrDate){
    //2017-10-17   or  2017-10
    var calendar = new GregorianCalendar();
    var returnDate = "";
    try {

        var df;
        if(billMonthOrDate.length() > 7){
            df = new SimpleDateFormat("yyyy-MM-dd");
        }else{
            df = new SimpleDateFormat("yyyy-MM");
        }
        var billDate = df.parse(billMonthOrDate);
        calendar.setTime(billDate);
        calendar.add(Calendar.MONTH, 1);
        var resultDate = calendar.getTime();
        returnDate = df.format(resultDate);

    } catch (e) {
        logger.error(e);
        statCaughtException(context, e);
    }

    return returnDate;
}

function setValueForBillUSDCredit(billAllData){
    billAllData.setUsdNewBalance(null);
    billAllData.setUsdMinPayment(null);
    billAllData.setUsdLastBalance(null);
    billAllData.setUsdLastPayment(null);
    billAllData.setUsdNewCharges(null);
    billAllData.setUsdInterest(null);
    billAllData.setUsdCreditLimit(null);
    billAllData.setUsdCashLimit(null);
}


var luaFuncs = {

    /**
     * 用LUA登录首页获取到cookies
     */
    loginHtmlGetCookies: function () {
        var map = new LinkedHashMap();
        map.put("method", "loginHtmlGetCookies");
        return sendAndReceive(map);
    },

    getHtml2:function () {
        var map = new HashMap();
        map.put("method","getHtml2");
        return sendAndReceive(map);
    },
    refreshImage:function(){
        var map = new HashMap();
        map.put("method","refreshImage");
        return sendAndReceive(map);
    },
    reloadHtml : function (accountId,billYM) {
        var map = new HashMap();
        map.put("method","reloadHtml");
        map.put("billYM",billYM);
        map.put("accountId",accountId);
        return sendAndReceive(map);
    },

    pf_ajax_post: function( url, postdata, outtime) {
        var map = new LinkedHashMap();
        var sb = new StringBuffer();
        for each(var key in postdata.keySet()) {
            sb.append(key + "=" + postdata.get(key) + "&");
        }
        var data = "";
        if (sb.length() > 0) {
            data = sb.substring(0, sb.length() - 1);
        }
        map.put("method", "ajax_post");
        map.put("url", url);
        map.put("data", data);
        map.put("timeout", outtime);
        return sendAndReceive(map);
    },
    pf_ajax_get: function(url, outtime){
        var map = new LinkedHashMap();
        map.put("method", "ajax_get");
        map.put("url", url);
        map.put("timeout", outtime);
        return sendAndReceive(map);
    },
    click_login_button: function(){
        var map = new LinkedHashMap();
        map.put("method", "click_login_button");
        return sendAndReceive(map);
    },
    getLoginDataA:function () {
        var map = new LinkedHashMap();
        map.put("method", "getLoginDateA");
        return sendAndReceive(map);
    },
    getLoginDataB:function () {
        var map = new LinkedHashMap();
        map.put("method", "getLoginDateB");
        return sendAndReceive(map);
    },
    click_login_button_before_SmsWaitValue:function () {
        var map = new LinkedHashMap();
        map.put("method", "click_login_button_before_SmsWaitValue");
        return sendAndReceive(map);
    },
    selectAccount : function(){
        var map = new LinkedHashMap();
        map.put("method", "selectAccount");
        return sendAndReceive(map);
    },
    selectBillMonth : function(i){
        var map = new LinkedHashMap();
        map.put("method", "selectBillMonth");
        map.put("index", i);
        return sendAndReceive(map);
    },
    jumpToBill : function(){
        var map = new LinkedHashMap();
        map.put("method", "jumpToBill");
        return sendAndReceive(map);
    },
    closeErrorMsgButton : function(){
        var map = new LinkedHashMap();
        map.put("method", "closeErrorMsgButton");
        return sendAndReceive(map);
    },
    changeImg : function(){
        var map = new LinkedHashMap();
        map.put("method", "changeImg");
        return sendAndReceive(map);
    },
    //如果页面提示了错误信息，本方法将错误信息清除掉，不然错误信息还会留在页面上重试的时候还会取到这个错误信息导致我们的判断不正确，
    clearErrorMsg : function(){
        var map = new LinkedHashMap();
        map.put("method", "clearErrorMsg");
        return sendAndReceive(map);
    },
    //检查用户名，验证码，密码是否输入正常（参数1：id, 参数2：正确的值）
    checkIfInput : function(id,value){
        var map = new LinkedHashMap();
        map.put("method", "checkIfInput");
        map.put("id", id);
        map.put("value", value);
        return sendAndReceive(map);
    },
    faindCardlist : function(id,value){
        var map = new LinkedHashMap();
        map.put("method", "faindCardlist");
        return sendAndReceive(map);
    },
    mouseMoveClick : function(){
        var map = new LinkedHashMap();
        map.put("method", "mouseMoveClick1");
        return sendAndReceive(map);
    },
    setSizeAndShow : function(){
        var map = new LinkedHashMap();
        map.put("method", "setSizeAndShow");
        return sendAndReceive(map);
    },
    threadSleep : function(){
        var map = new LinkedHashMap();
        map.put("method", "threadSleep");
        return sendAndReceive(map);
    },
}